import to from '@/utils/to'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { ProductApi } from '@/api/product'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { BrandRes, BrandForm, BrandModel } from '@/api/product/type'

// 品牌逻辑层
export const useBrand = () => {
  const loading = ref(false)
  const dialogFormVisible = ref(false)
  const dialogTitle = ref<string>('添加品牌')
  const page = ref<number>(1) // 当前页数
  const limit = ref<number>(5) // 每页大小
  const total = ref<number>(0)
  const brandList = ref<BrandModel[]>()
  const brandForm = reactive<BrandForm>({ tmName: '', logoUrl: '' })
  const formRef = ref<FormInstance>()
  const brandRules = <FormRules<BrandForm>>{
    tmName: [
      { required: true, message: '请输入品牌名称', trigger: 'blur' },
      { min: 2, max: 20, message: '品牌长度为2-20个字符', trigger: 'blur' }
    ],
    logoUrl: [{ required: true, message: '请上传品牌LOGO图片', trigger: 'blur' }]
  }

  // 获取品牌列表
  const getBrandList = async (pager: number = 1) => {
    page.value = pager
    loading.value = true
    let response: BrandRes = await ProductApi.brandList(page.value, limit.value)
    total.value = response.total
    brandList.value = response.records
    loading.value = false
  }

  const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    // 图片上传成功，清除验证信息
    formRef.value?.clearValidate()
    brandForm.logoUrl = response.data
  }

  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const fileSuffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
    const whiteList = ['jpg', 'jpeg', 'png', 'gif']
    if (whiteList.indexOf(fileSuffix) === -1) {
      ElMessage.error('上传文件仅限jpg|jpeg|png|gif格式')
      return false
    }
    if (rawFile.size / 1024 / 1024 > 10) {
      ElMessage.error('图片大小不能超过10M!')
      return false
    }
    return true
  }

  // 添加品牌对话框
  const showBrandDialog = (item: BrandModel | undefined) => {
    formRef.value?.clearValidate()
    if (item) dialogTitle.value = '编辑品牌'
    brandForm.id = item?.id
    brandForm.tmName = item?.tmName ?? ''
    brandForm.logoUrl = item?.logoUrl ?? ''
    dialogFormVisible.value = true
  }

  // 删除
  const deleteHandle = async (row: BrandModel) => {
    try {
      await ProductApi.brandDelete(row.id)
      ElMessage.success('删除成功')
      getBrandList(brandList.value!.length > 0 ? page.value : page.value - 1)
    } catch (error) {}
  }

  // 表单提交事件
  const submitHandle = async () => {
    try {
      if (await to(formRef.value!.validate())) return
      await ProductApi.brandEdit(brandForm)
      ElMessage.success('添加成功')
      getBrandList()
      dialogFormVisible.value = false
    } catch (error) {}
  }

  return {
    loading,
    dialogFormVisible,
    dialogTitle,
    page,
    limit,
    total,
    brandList,
    brandForm,
    formRef,
    brandRules,
    getBrandList,
    handleAvatarSuccess,
    showBrandDialog,
    beforeAvatarUpload,
    deleteHandle,
    submitHandle
  }
}
